<template>
    <div class="pay_baohutong">
        <!-- 查询 -->
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="账户类型" prop="accountType">
                            <el-select v-model="form.accountType" placeholder="全部类型">
                                <el-option
                                    v-for="item in accountType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="主体名称" prop="merchantName">
                            <el-input
                                v-model="form.merchantName"
                                clearable
                                placeholder="请输入姓名/或企业名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="来源门店" prop="shopId">
                            <el-select v-model="form.shopId" filterable @focus="getShopList" placeholder="全部门店">
                                <el-option
                                    v-for="item in shopList"
                                    :key="item.shopId"
                                    :label="item.shopName"
                                    :value="item.shopId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创建时间" prop="accountTime">
                            <el-date-picker
                                v-model="form.accountTime"
                                type="datetimerange"
                                range-separator="至"
                                :default-time="defaultTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="pay_baohutong_bottom">
            <!-- 按钮 -->
            <div class="btn-group" v-auth="'baohu_manage:edit'">
                <!-- 开通账户 -->
                <OpenAccountDialog />
                <!-- 绑定账户 -->
                <BindAccountDialog @handle-confirm="queryListHandler" />
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <template v-if="prop === 'merchantName'">
                            {{ row?.merchantName || '-' }}<br />{{ row?.loginNo }}
                        </template>
                        <template v-if="prop === 'shopRelation'">
                            <span v-for="item in row?.shopRelation" :key="item.id">
                                <span>{{ item.shopName }}</span
                                ><br />
                            </span>
                            <span v-if="!row?.shopRelation || !row?.shopRelation?.length">-</span>
                        </template>
                        <template v-if="['withdrawableAmount', 'settledAmount'].includes(prop)">
                            <!-- 已开户才展示，未开始显示【-】 -->
                            <div class="custom-el-link" v-if="getSum(row, prop)">
                                <span @click="nameRouteHandler(row, prop)"
                                    >￥{{ floatDivide(row[prop], 100).toFixed(2) }}</span
                                >
                            </div>
                            <div v-else>
                                <span>-</span>
                            </div>
                        </template>
                        <template v-if="prop === 'operations'">
                            <template v-for="{ label, fn, ref, auth } in row.operations" :key="label">
                                <el-button
                                    v-if="label === '默认账户'"
                                    size="small"
                                    disabled
                                    style="background: #ff6b00; color: #fff">
                                    {{ label }}
                                </el-button>
                                <el-button v-else @click="fn(row, ref)" size="small" v-auth="auth">
                                    {{ label }}
                                </el-button>
                            </template>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
    </div>
</template>

<script setup name="payBaohutong">
import { ref, reactive, computed, onActivated, onDeactivated } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { floatDivide, packSelectObjUtil, cloneDeep, format } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import BindAccountDialog from './bindAccountDialog.vue';
import OpenAccountDialog from './openAccountDialog.vue';
import { getShopListHook } from '@/hooks';

const router = useRouter();

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const accountType = reactive(packSelectObjUtil(constants.BAOHU_ACCOUNT_TYPE));

const form = reactive({
    page: 1, // 分页页码，数字类型
    perPage: 10, // 默认每页15条
    accountType: 0, // 账户类型
    merchantName: '', // 企业/个人/个体名称
    accountTime: null,
    shopId: 0
});
let formClone = cloneDeep(form);
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '账户类型', prop: 'accountTypeName', width: '120' },
        { label: '主体名称/登录号', prop: 'merchantName', showOverflowTooltip: true, minWidth: '200' },
        { label: '关联门店', prop: 'shopRelation', showOverflowTooltip: true, minWidth: '150' },
        { label: '进度', prop: 'accountStatusName', width: '120' },
        { label: '可提现金额', prop: 'withdrawableAmount', showOverflowTooltip: true, minWidth: '120' },
        { label: '待结算金额', prop: 'settledAmount', showOverflowTooltip: true, minWidth: '120' },
        { label: '创建时间', prop: 'accountTimeText', width: '200' },
        { label: '操作', prop: 'operations', width: '160', fixed: 'right' }
    ];
    return baseTableColumns;
});

const nameRouteHandler = ({ loginNo }) => {
    // const { href } = router.resolve({
    //     path: '/pay/baohutong/detail',
    //     query: {
    //         id,
    //         activeName: 'account'
    //     }
    // });
    // window.open(href, '_blank');
    router.push({
        path: '/pay/baohutong/detail',
        query: {
            no: loginNo,
            activeName: 'account'
        }
    });
};
/**
 * 设置默认账户
 */
const setDefaultAccountHandle = async row => {
    await ElMessageBox.confirm('确定修改默认账户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    });
    await request('setDefaultAccountServ', {
        loginNo: row.loginNo
    });
    ElMessage.success('设置成功');
    queryListHandler();
};
const routerHandler = (row, ref) => {
    const paths = {
        1: 'enterprise', // 企业账户
        2: 'individual', // 个体账户
        3: 'person' // 个人账户
    };
    router.push({
        path: '/pay/baohutong/' + paths[row?.accountType],
        query: { no: row?.loginNo, paySequenceNo: row?.paySequenceNo }
    });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryListHandler();
};

// 获取来源店铺
let shopList = reactive([{ shopId: 0, shopName: '全部门店' }]);
const getShopList = async () => {
    if (shopList.length <= 1) {
        const { data } = await getShopListHook();
        shopList.length = 0;
        const list = data.list;
        list.unshift({ shopId: 0, shopName: '全部门店' });
        Object.assign(shopList, list);
    }
};
/**
 * 分页查询
 */
const queryListHandler = async () => {
    const _form = cloneDeep(form);
    _form.accountType = _form.accountType || null;
    _form.shopId = _form.shopId || null;
    const res = await request('baofuBhtAccountList', _form);
    const list = (res?.data?.data || []).map((item, i) => {
        const { accountStatus, accountType } = item;
        item.accountTimeText = format(item.accountTime, 'YYYY-MM-DD HH:mm:ss');
        item.accountStatusName = item.accountStatusName || '-';
        // 根据不同状态显示不同按钮
        // 立即绑卡 详情 上传资料 微信报备 微信签约
        const btns = {
            0: { label: '立即绑卡', fn: routerHandler, ref: 'bindButtonRef', auth: 'baohu_manage:edit' },
            1: { label: '详情', fn: nameRouteHandler, ref: 'infoButtonRef', auth: 'baohu_manage:edit' },
            2: { label: '上传资料', fn: routerHandler, ref: 'uploadButtonRef', auth: 'baohu_manage:edit' },
            3: { label: '微信报备', fn: routerHandler, ref: 'reportButtonRef', auth: 'baohu_manage:edit' },
            4: { label: '微信签约', fn: routerHandler, ref: 'signButtonRef', auth: 'baohu_manage:edit' },
            5: { label: '默认账户' },
            6: { label: '设为默认', fn: setDefaultAccountHandle, ref: 'signButtonRef', auth: 'baohu_manage:edit' }
        };
        item.operations = [];
        if (accountType == 1) {
            // 企业账户
            if (accountStatus == 2) {
                // 待上传资料
                item.operations = [btns[2]];
            } else if (accountStatus == 8) {
                // 已开户_待报备
                item.operations = [btns[3], btns[1]];
            } else if (accountStatus == 9) {
                // 已报备
                item.operations = [btns[4], btns[1]];
            } else if (accountStatus == 10) {
                // 已签约
                item.operations = [btns[1]];
                item.isDefault === 1 ? item.operations.push(btns[5]) : item.operations.push(btns[6]);
            }
        } else if (accountType == 2) {
            // 个体账户
            if (accountStatus == 2) {
                // 待上传资料
                item.operations = [btns[2]];
            } else if ([11, 12].includes(accountStatus / 1)) {
                // 已开户_待绑卡
                item.operations = [btns[0], btns[1]];
            } else if ([8].includes(accountStatus / 1)) {
                // 已开户_待报备
                item.operations = [btns[3], btns[1]];
            } else if (accountStatus == 9) {
                // 已报备
                item.operations = [btns[4], btns[1]];
            } else if (accountStatus == 10) {
                // 已签约
                item.operations = [btns[1]];
                item.isDefault === 1 ? item.operations.push(btns[5]) : item.operations.push(btns[6]);
            }
        } else if (accountType == 3) {
            // 个人账户
            if ([11, 12].includes(accountStatus / 1)) {
                // 11已开户_待绑卡 12已发短信_待绑卡
                item.operations = [btns[0], btns[1]];
            } else if (accountStatus == 13) {
                // 已绑卡
                item.operations = [btns[1]];
            }
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res?.data?.total;
};
// 是否显示金额
const getSum = (row, prop) => {
    let status = false;
    if (row?.accountType == 1) {
        status = [8, 9, 10].includes(row.accountStatus);
    } else if (row?.accountType == 2) {
        status = [8, 9, 10, 12, 13].includes(row.accountStatus);
    } else if (row?.accountType == 3) {
        status = [11, 12, 13].includes(row.accountStatus);
    }
    return status && ![null, undefined].includes(row[prop]);
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};

const visibilitychange = () => {
    // 页面可见
    if (document.visibilityState === 'visible') {
        queryListHandler();
    }
};

const getAllData = () => {
    queryListHandler();
};

onActivated(() => {
    // Object.keys(formClone || {})?.forEach(key => {
    //     form[key] = formClone[key];
    // });
    getAllData();
    setLayout('pay-baofutong-layout');
    // useDocumentVisibility('add', visibilitychange);
});
onDeactivated(() => {
    resetLayout('pay-baofutong-layout');
    // useDocumentVisibility('remove', visibilitychange);
});

onBeforeRouteLeave((to, from, next) => {
    if (!/\/marketing\/coupon/.test(to?.path)) {
        Object.keys(formClone || {})?.forEach(key => {
            form[key] = formClone[key];
        });
    }
    next();
});
</script>
<style lang="scss">
.pay-baofutong-layout {
    height: 100%;
    padding: 0 !important;
    background-color: #f3f3f3 !important;
}
.custom-pay-confirm-class {
    width: 300px;
    .el-message-box__title {
        justify-content: flex-start;
    }
    .el-message-box__message {
        margin: 20px 0;
        font-size: 16px;
    }
    .el-button {
        width: 100px;
        margin-bottom: 10px;
    }
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
